<?php
namespace app\store\controller;
use think\Db;
use think\request;
use think\Controller;
use app\common\controller\PaylogBaseController;
use app\index\model\AgentModel;
use app\agent\model\GoodsModel;
class Agent extends Controller
{
	protected function _initialize() {
		header('Access-Control-Allow-Origin:*');
		$type=get_brower_type();
	}
	public function index(){
		$type=get_brower_type();//判断是微信还是支付宝打开
    	$redirect='https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		if(isset($_SERVER['HTTP_REFERER'])){
			$agent_info = db('info_agent')->where('id',session("agent_id"))->find();
			$this->assign("agent_info",$agent_info);
			return $this->fetch();
		}
		if(session("agent_id")){
			$agent_info = db('info_agent')->where('id',session("agent_id"))->find();
			$this->assign("agent_info",$agent_info);
			return $this->fetch();
		}
    	if($type==1){
			$auth_code=input("auth_code");
			$url ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.config('alipay_appid').'&scope=auth_base&redirect_uri='.urlencode($redirect);
		}elseif($type==2){
			$auth_code=input("code");
			$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect';
		}else{
			$agent_info = db('info_agent')->where('id',session("agent_id"))->find();
			$this->assign("agent_info",$agent_info);
			return $this->fetch();
			//$this->redirect('store/agent/index');
		}
		if(!$auth_code){
			Header("Location: $url");
			exit;
		}else{
			if($type==1){//支付宝openid
				$field="alipay_id";
				$openid=user_ali_id($auth_code);
				
			}elseif($type==2){//微信openid
				$field="openid";
				if(session('cut_auth_code') != $auth_code && session('prior_auth_code') != $auth_code){
					session('prior_auth_code',session('cut_auth_code'));
					session('cut_auth_code',$auth_code);
					$openid=user_wx_id($auth_code);
				}else{
					Header("Location: $url");
					exit;
				}
			}
    	}
    	$user_info = db('info_user')->where($field,$openid)->find();
		if($user_info){
			session("info_user",$user_info);
			if($user_info['is_agent']==2){
				$agent_info = db('info_agent')->where('user_id',$user_info['id'])->find();
				if(!$agent_info['operation_pwd']){
					$res = db('info_agent')->where("id",$agent_info['id'])->update(['operation_pwd' => '25065982906c2a323b0b5c555ddb76d2']);	
				}
				$this->assign("agent_info",$agent_info);
				session("agent_id",$agent_info['id']);
			}else{
				return $this->fetch("error");
			}
		}else{
			return $this->fetch("error");
		
		}
		return $this->fetch();
	}
	
	//商家信息
    public function agent()
    {
    	$agent_id = session('agent_id');  	
    	if(request()->isPost()){
    		$param=input('post.');
    		$agent_model = new AgentModel();
    		$param['add_time']	= now_time();
    		$rest=$agent_model->where('id',$agent_id)->update($param);
    		if($rest){
    			return json(['code'=>200,'msg'=>'修改成功']);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
    	}
    	
    	$agent_info = db('info_agent')->where('id',$agent_id)->find();  	
    	$this->assign("agent_info",$agent_info);
       	return  $this->fetch();
    }
	
	//门店信息
    public function shop_list()
    {
    	$agent_id = session('agent_id');

		$where['order_type'] = ['not in',[3,4,5]];
		$where['agent_id'] = $agent_id;
		$where['state'] = 2;
		$field="agent_id,chain_id,sum(balance) as balance";
		$res=db("log_paylog")->field($field)->where($where)->group('chain_id')->buildSql();
		
		$wheres['a.agent_id'] = $agent_id;
		$wheres['a.state'] = 1;
		$agent_store = db('agent_store')->alias('a')
		->join('info_agent c','c.id = a.agent_id','LEFT')
		->join($res.' b','b.chain_id = a.id','LEFT')
		->field('a.id,a.store_name,b.balance,c.logo')
    	->where($wheres)
    	->select();	
		
    	$this->assign("agent_store",$agent_store);
       	return  $this->fetch();
    }
	
	//员工信息
    public function employeemage()
    {
    	$agent_id = session('agent_id');

    	$where['a.agent_id'] = session('agent_id');
    	$where['a.state'] = ['not in',3];
		$data=Db::table('agent_clerk')
    	->alias('a')
    	->join('agent_store w','a.chain_id = w.id')
    	->field('a.*,w.store_name store_name')
    	->where($where)
    	->order('a.add_time desc')
		->paginate(20);
		$this->assign('data',$data);
		$this->assign('agent_id',$agent_id);
       	return  $this->fetch();
    }
    
	//员工信息
    public function employee_memadd()
    {
    	$this->assign('agent_id',input("agent_id"));
       	return  $this->fetch();
    }
	
	//获取连锁店列表
	public function get_chainstore(){
		$chianlist = db("agent_store")->field("id,store_name,addres")->where('agent_id',input("agent_id"))->where('state',1)->select();
		return json(["chianlist"=>$chianlist]);
	}
	
	/**
	 * 创建员工
	 */
	public function create_emp(){
		//根据用户id查找用户信息
    	$agent_info = db('info_agent')->where('id',input('agent_id'))->find();		
    	$store_id = $agent_info['id'];
		$param = input();
	  	//判断是否已是收银员
		$clerk_info = db('agent_clerk')->where('mobile',$param["mobile"])->where('state','<>','3')->find();
		if($clerk_info){
			return json(['code'=>405,'msg'=>'当前用户已是收银员']);
		}
		
	    //获取用户信息，openid不为空
		$user_info = db('info_user')->where('id',$param["no"])->where('openid','<>','')->find();
	    if($user_info){
			$storeinfo=db('agent_store')->where('id',input("chain_id"))->find();
			$union_data['agent_id'] 		= input('agent_id');
			$union_data['no'] 				= $param['no'];
			$union_data['password'] 		= md5_salt($param['pwd']);
			$union_data['chain_id'] 		= $param['chain_id'];
			$union_data['ctype'] 			= $param['z_id'];
			$union_data['mobile'] 			= $param["mobile"];
			$union_data['name'] 			= $param['name'];
			$union_data['add_time'] 		= now_time();
			$union_data['oem_id'] 			= 1;
			$union_data['user_id'] 			= $user_info['id'];
			$res = db('agent_clerk')->insert($union_data);
			if($res){
				return json(['code'=>200,'msg'=>'添加成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'添加失败']);
			}
		}else{
			return json(['code'=>405,'msg'=>'当前用户不是会员']);
		}
    }

	//商家红包
	public function hongb_list(){
		$where['agent_id'] = session('agent_id');
//		$where['status'] = 1;
		$list=db("agent_activegold")->where($where)->order("add_time desc ")->select();
		$this->assign('list',$list);
		return $this->fetch();
	}
	
	//红包领取页面
	public function hongb_page(){
		Db::startTrans();
		$hb_id=input('m');
		$user_id=session('info_user')['id'];
		$hb=db("agent_activegold")->alias("a")->lock(true)->
		join("info_agent b","a.agent_id=b.id")->field("a.*,b.agent_name,b.logo")->
		where("a.id",$hb_id)->find();
		if(!$hb){
			echo '访问页面不存在!!!';
			exit;
		}
		$message="";
		$count=0;//当前领取人数
		$status=1;//红包状态
		if($hb['end_time']<now_time()){
			$message="红包已过期";
			$status=0;
			$this->redirect('hongb_gq');
			exit;
		}
		if($hb['peoples']>=$hb['user_num']){
			$message="红包已领完";
			Db::rollback();
			$status=0;
		}
		if($hb['sums']>$hb['gold_sum']){
			echo '红包已经领完!!!';
			exit;
		}
		$gold_num=0;//我领取的
		$list=db("agent_activelog")->where("gold_id",$hb_id)->order("add_time desc")->select();
		if($list){//判断我是否已经领取过
			foreach($list as $k){
				if($k['user_id']==$user_id){
					$status=0;
					$gold_num=$k['gold_num'];
					break;
				}
			}
		}
		$hb['sums']=sprintf("%.2f",$hb['sums']);
		if($status==1){
			$result=true;
			//平均红包
			if($hb['hb_type']==1){
				if($hb['user_num']-$hb['peoples']==1){
					$up['status']=2;
					$gold_num=$hb['gold_sum']-$hb['sums'];
				}else{
					$gold_num=sprintf("%.2f",$hb['gold_sum']/$hb['user_num']);
				}
				
			}else{
				//如果是最后一个红包用红包总金额减去已经领取的
				if($hb['user_num']-$hb['peoples']==1){
					$up['status']=2;	
					$gold_num=$hb['gold_sum']-$hb['sums'];
				}else{
					$p=$hb['user_num']-$hb['peoples'];
					//当前剩余的
					$belive_sum=sprintf("%.2f",$hb['gold_sum']-$hb['sums']);
					$max=sprintf("%.2f",$belive_sum/$p*3*100);
					$gold_num=rand(1,$max)/100;
					if($gold_num>=$belive_sum||$gold_num==0){
						$gold_num = sprintf("%.2f",$belive_sum/$p*100000/100000);
					}
				}
			}
			$up['peoples']=['exp',"peoples+1"];
			$up['sums']=['exp',"sums+$gold_num"];
			$res=db("agent_activegold")->where("id",$hb_id)->update($up);
			if($res){
				$res=db("info_user")->where("id",$user_id)->setInc('score',$gold_num);
				if($res){
					$res=user_score_change($user_id,12,$gold_num,
					'领取鼓励金红包',0,0);
					if(!$res){
						$result=FALSE;
					}
				}else{
					$result=FALSE;
				}
			}else{
				$result=FALSE;
			}
			
			$res=$this->add_hblog($hb['id'],session("info_user")['id'],session("info_user")['mobile'],$gold_num,session("info_user")['user_name'],session("info_user")['logo']);
			if(!$res){
				$result=FALSE;
			}
		}else{
			$result=false;
		}
		$this->assign('gold_num',$gold_num);
		if($result){
			Db::commit();
		}else{
			Db::rollback();
		}
		$url=config('API_DOMAIN')."store/agent/hongb03?m=$hb_id";
		$this->assign("url",$url);
		$this->assign('hb',$hb);
		$this->assign('list',$list);
		$this->assign('count',$hb['peoples']);
		$this->assign('status',$status);
		$this->assign('message',$message);
		return $this->fetch();
	}
	
	public function add_hblog($gold_id,$user_id,$mobile,$gold_num,$user_name,$logo){
		$type=get_brower_type();
		if($user_name){
			
		}else{
			if($type==1){
			  $user_name='支付宝会员';
			}else{
			  $user_name='微信会员';
			}
		}
		$data['gold_id']=$gold_id;
		$data['user_id']=$user_id;
		$data['mobile']=$mobile;
		$data['gold_num']=$gold_num;
		$data['user_name']=$user_name;
		$data['logo']=$logo?$logo:"/public/static/index/images/member.jpg";
		$data['add_time']=now_time();
		$res=db("agent_activelog")->insert($data);
		return $res;
	}
	
	//红包领取记录
	public function hongb_logo(){
		Db::startTrans();
		$hb_id=input('m');
		$user_id=session('info_user')['id'];
		$hb=db("agent_activegold")->alias("a")->lock(true)->
		join("info_agent b","a.agent_id=b.id")->field("a.*,b.agent_name,b.logo")->
		where("a.id",$hb_id)->find();
		if(!$hb){
			echo '访问页面不存在!!!';
			exit;
		}
		$list=db("agent_activelog")->where("gold_id",$hb_id)->order("add_time desc")->select();
		$this->assign('hb',$hb);
		$this->assign('list',$list);
		$this->assign('count',$hb['peoples']);
		return $this->fetch();
	}
	
	//拼手气红包
	public function hongb_pin(){
		$agent_id = session('agent_id');
    	$info_agent = db('info_agent')->where('id',$agent_id)->field('score')->find();
    	$this->assign('info_agent',$info_agent);
		return  $this->fetch();
	}
	//普通红包
	public function hongb_put(){
		$agent_id = session('agent_id');
    	$info_agent = db('info_agent')->where('id',$agent_id)->field('score')->find();
    	$this->assign('info_agent',$info_agent);
		return  $this->fetch();
	}
	
	//发送红包
	public function send_hb(){
		$agent_id = session('agent_id');
		$data['type']=input('type');
		$data['agent_id']=$agent_id;
		$data['user_id']=session('info_user')['id'];
		$data['gold_sum']=input("hbmoney");//红包金额
		$data['user_num']=input("hbnums");//红包个数
		$data['hb_type']=input('hbtype');
		$data['add_time']=now_time();
		$data['end_time']=date('Y-m-d H:i:s',strtotime('+1 day'));
		$data['memo']=input('memo')?input('memo'):'[鼓励金红包]鼓励金可以在附近的合作商家消费抵现';
		$info_agent = db('info_agent')->where('id',$agent_id)->field('id,operation_pwd,score')->find();
		$pwd=input("pwd");
		if(!$pwd){
			return json(['code'=>403,'msg'=>'操作密码错误']);
		}
		if($info_agent['operation_pwd'] != md5_salt($pwd)){
			return json(["code"=>403,'msg'=>'操作密码错误']);
		}
		if($info_agent['score']<input('hbmoney')){
			return json(['code'=>400,'msg'=>'鼓励金余额不足']);
		}else{
			$res=db('agent_activegold')->insertGetId($data);
			if($res){
				$res1=db("info_agent")->where("id",$info_agent['id'])->setDec("score",input("hbmoney"));
				if($res1){
					$paylog = new PaylogBaseController();
					//商家鼓励金记录 	
					$paylog->agent_score_log(session("agent_id"),10,-$data['gold_sum'],"创建红包活动扣除:".$data['gold_sum'],0,0);
					return json(['code'=>200,'msg'=>'操作成功','id'=>$res]);	
				}
			}
			return json(['code'=>400,'msg'=>'操作失败']);
		}
	}

	public function hongb02(){
		$hb=db("agent_activegold")->find(input("m"));
		$url=config('API_DOMAIN')."store/agent/hongb03?m=".input("m");
		$this->assign('url',$url);
		$code_url= 'http://www.vshop88.net/code/code.php?url='.urlencode($url).'&margin=1&size=10';
		$this->assign("code_url",$code_url);
		$this->assign('hb',$hb);
		return $this->fetch();
	}
	//红包开页面
	public function hongb03(){
		$hb=db("agent_activegold")->where("id",input("m"))->find();
		if(!$hb){
			echo '访问错误';
			exit;
		}
		$type=get_brower_type();//判断是微信还是支付宝打开
		$redirect=config('API_DOMAIN')."store/agent/hongb03?m=".input("m");
		$openid=session("openid");
		if(!$openid){
			if($type==1){
				$auth_code=input("auth_code");
				$url ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.config('alipay_appid').'&scope=auth_base&redirect_uri='.urlencode($redirect);
			}else{
				$auth_code=input("code");
				$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_base&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect';
			}
			if(!$auth_code){
				Header("Location: $url");
				exit;
			}
		}
		if($type==1){//支付宝openid
			$field="alipay_id";
			$pay_type=3;
			if(!$openid){
				$openid=user_ali_id($auth_code);
			}
		}elseif($type==2){//微信openid
			$field="openid";
			$pay_type=2;
			if(!$openid){
				$openid=user_wx_id($auth_code);
			}
		}	
		session('openid',$openid);
		$send_user=db("info_user")->find($hb['user_id']);
		if($openid){
			$w_u[$field]=$openid;
			$user=db('info_user')->where($w_u)->find();
			if(!$user){
				$data[$field]			= $openid;
				$data['level']			= $send_user['id'];
				$data['agency_id1']		= $send_user['agency_id1'];
				$data['agency_id2']		= $send_user['agency_id2'];
				$data['oem_id']			= 1;
				$data['salesman_id']	= $send_user['salesman_id'];
				$data['tj_agent']		= $send_user['tj_agent'];
				$data['tj_pt']			= $send_user['tj_pt'];
				$data['add_time']		= now_time();
				$user_id=Db::name('info_user')->insertGetId($data);
				$this->assign('flag',2);
			}else{
				$user_id=$user['id'];
				//1 已注册 2 未注册  
				$this->assign('flag',1);
				$list=db("agent_activelog")->where("gold_id",input("m"))->select();
				if($list){//判断我是否已经领取过
					foreach($list as $k){
						if($k['user_id']==$user_id){
							$this->assign('flag',3);//已领取过
							break;
						}
					}
				}	
			}			
		}
		$user=db("info_user")->where("id",$user_id)->find();
		session("info_user",$user);
		$this->assign('user',$send_user);
		$this->assign('hb',$hb);
		return $this->fetch();
	}
	
	public function hongb_gq(){
		return $this->fetch();
	}
	
	 /**
	  * 商家鼓励金变化记录
	  */
	public function score_record(){
		$where['agent_id'] = session('agent_id');	
		$code_url="http://".$_SERVER['HTTP_HOST']."/index/pay/recharge?user_id=".session('agent_id')."&user_type=2&change_type=1&";
		$this->assign('code_url',$code_url);
		return $this->fetch();
	}
	
	//商家鼓励金变化记录
	function score_records(){
		$agent_id = session('agent_id');  	
		$page=1;
		if(input("page")){
			$page=input("page");
		}
		$begin=($page-1)*10;
		$record_list = db('log_agent_score')->where('agent_id',$agent_id)->order('add_time desc')->limit($begin,10)->select();	
		return json(["list"=>$record_list]);
	}
	
	//超级玛支付跳转
	function  querfuk(){
		$url=config('WEB_DOMAIN')."wallet/querfuk.html?fromuid=".input("fromuid")."&store_id=".input("store_id");
		if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {  
			Header("Location: $url");exit;
	   	}elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false) {
	       	Header("Location: $url"); exit;
	    }else{
	    	$agent=db('info_agent')->find(input("store_id"));
			$this->assign("fromuid",input("fromuid"));
			if(input("chain_id")){
				$this->assign("chain_id",input("chain_id"));
			}else{
				$this->assign("chain_id","");
			}
			$this->assign("store_id",input("store_id"));
			$this->assign("agent",$agent);
			$this->assign("sn",order_create_no());
			if(input("user_id")){
				$parent=db("member")->field("pt_id")->find(input('fromuid'));
				$member=db('member')->where("cbc_id",input("user_id"))->find();
				if(!$member){
					$data['pid']=input('fromuid');
					$data['pt_id']=$parent['pt_id'];
					$data['status']=0;
					$data['agent_type']=1;
					$data['add_time']=now_time();
					$data['cbc_id']=input("user_id");
					db("member")->insert($data);
					$member=db('member')->getLastInsID();
				}
				$this->assign("member",$member);
			}else{
				 echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><script>alert('请先登录建行app')</script>";exit;
			}
	    	return $this->fetch();
	    }
		
	}
//获取连锁店营业数据
	public function chain_data(){
		$chain=db("mall_chainstore")->field("emp_no,name")->find(input("chain_id"));
		$where['chainstore_id']=input("chain_id");
		$where['mobile']=input("mobile");
		$emp=db('line_employee')->where($where)->field("id,no")->find();
		if($chain['emp_no']==$emp['no']){//判断当前用户是否是值班人员
			$wh['chain_id']=input("chain_id");
			$wh['employee_id']=$emp['id'];
			$start_time=db("line_shift")->where($wh)->field("add_time")->order("add_time desc ")->find();
			if($start_time){
				$cw['c.add_time']=[">=",$start_time['add_time']];
			}else{
				$start_time=date('Y-m-d 00:00:00',time());
				$cw['c.add_time']=[">=",$start_time];
			}
			$cw['c.type'] = ["in","ads_order,score_pay,uesr_payee"];
			$cw['c.chain_id']=input("chain_id");
			$field="c.price,c.type,c.add_time,m.mobile,m.is_atten,m.thumb,m.wx_headimg";
			$list=db("mall_corepaylog")->alias("c")->
			join("long_member m","c.uid=m.id")
			->field($field)->where($cw)->select();
			if($list){
				return json(["code"=>200,"data"=>$list,'chain'=>$chain]);				
			}else{
				return json(["code"=>404,'chain'=>$chain]);
			}
		}else{
			return json(["code"=>406,'msg'=>'用户不在值班中','chain'=>$chain]);				
		}
	}
	//添加职位
	public function add_zw(){
		$data['agent_id']=input("agent_id");
		$data['name']=input("name");
		$res=db("line_zhiwei")->insert($data);
		if($res){
			return json(['code'=>200]);
		}else{
			return json(['code'=>404]);
		}
	}
	/**
	 * 商家申请提现
	 */
	public function tixian(){
			$balance = input('tixian_money'); 
			//手续费0.65%
			$poundage =0.0065;
			$store=db("info_agent")->where("u_id",input("uid"))->find();
			$now_time = date('H:i:s',time());
			$star_time = date('09:00:00',time());
			$end_time = date('17:00:00',time());
			if($now_time<$star_time||$now_time>$end_time)  {
				return $this -> toJson(408, '请在9:00~17:00时间段做提现操作');
			}			
			
			$map['createtime'] = ['between',[date('Y-m-d 00:00:00',time()),date('Y-m-d 23:59:59',time())]];
			$map['cash_status'] = array('in','1,2');
			$map['uid'] = $store['id'];
			$map['user_type'] = 2;
			$map['type'] = 1;
			$balancesum = db('mall_cashmanage')->where($map)->sum('balance');
			if($balancesum+$balance>1000)  {
				return $this -> toJson(408, '提现额度不足');
			}
			$jian_money = floatval(2);//提现手续费
			$act_money = floatval($balance)-floatval($jian_money);
 			//生成金额变化信息及修改商家余额
			$member_model = new Member();
			$result = $member_model -> insbalch($store['id'],"余额D+0提现",-$balance,2,0,1);
         	if ($result) {
	         	//新增提现记录
				$cashmanage['uid'] 				=  $store['id'];
				$cashmanage['user_type'] 		=  2;
				$cashmanage['type'] 			=  1;
				$cashmanage['balance'] 			=  $balance;
				$cashmanage['cash_type'] 		=  1;
				$cashmanage['actual_balance'] 	=  $act_money;
				$cashmanage['counter_fee'] 		=  $jian_money;
				$cashmanage['message'] 			=  $store['bank_account'];
				$cashmanage['cash_status'] 		=  1;
				$cashmanage['createtime'] 		=  now_time();
				$cashmanage['bank_account'] 	=  $store['bank_account'];
				$cashmanage['bank_username'] 	=  $store['bank_username'];
				$cashmanage['card_no'] 			=  $store['card_no'];
				$cashmanage['bank_mobile'] 		=  $store['bank_mobile'];
				$result1 = db('mall_cashmanage')->insert($cashmanage);
				
				// 获取短信模板
				$template = db('sms_template') -> find(5);
				$msg['name'] = $store['store_name'];
				//财务电话
				$cw_mobile = config('cw_mobile');
				//发送短信，提醒财务处理
				$msg = send_sms($cw_mobile, $template['tid'], json_encode($msg), $template['sign_name']);
				if($result1 ){
					return $this -> toJson(200, '申请提现成功');
				}else{
					return $this -> toJson(408, '申请提现失败');
				}
			}else{
				return $this -> toJson(408, '申请提现失败');
			}
	}
	//前台商家申请认证
	public function sq(){
			$data['is_credentials']=1;  
			$data['sq_time']=now_time();
			$data['card1']=input("card1");
			$data['card2']=input("card2");
			$data['card3']=input("card3");
			$data['license']=input("license");
			$data['bank_username']=input("bank_username");
			$data['card_no']=input("card_no");
			$data['bank_account']=input("bank_account");
			$data['idcard']=input("idcard");
			$data['bank_mobile']=input("bank_mobile");
			$data['bank_img']=input("bank_img");
			$res=db('info_agent')->where("u_id",input("uid"))->update($data);				
			
			// 获取短信模板
			$template = db('sms_template') -> find(6);
			$msg['product'] = '请立即处理';
			$msg['name'] = "商家".$data['bank_mobile'];
			//财务电话
			$cw_mobile = config('sh_mobile');
			//发送短信，提醒商家
			$msg = send_sms($cw_mobile, $template['tid'], json_encode($msg), $template['sign_name']);
				       
         	if ($res) {
                return $this -> toJson(200, '提交申请成功');
            } else {
                return $this -> toJson(404, '提交申请失败');
            }
	}
		//用户佣金转入余额
	function yonghj_to_money(){
		$user = db('info_agent')-> where('u_id', input('uid'))->find();
		
		if($user){
			$up_money = input('money');
			if($up_money<=$user['commission']){
				//剩余佣金
			   	$commission= bcsub($user['commission'], $up_money, 2);//扣除转入之后的佣金
			 	//手续费
			 	$poundage = bcmul($up_money, 0.05, 2);//费率
				//时间到账金额
				$add_money = bcsub($up_money, $poundage, 2);			//减
				
				$money = bcadd($user['store_balance'], $add_money, 2);	//加
				$total_balance = bcadd($user['total_balance'], $add_money, 2);	//加
				db('info_agent')->where('id', $user['id'])->update(['store_balance' => $money,'commission' =>$commission,'total_balance'=>$total_balance]);
				
				//扣除用户佣金
				$data['agent_id'] 			= $user['id'];
				$data['tid'] 			= 0;
				$data['balance'] 			= -$up_money;
				$data['add_time'] 		= now_time();
				$data['message'] 		= '佣金转余额-扣除佣金';
				$data['store_balance'] 		= $user['store_balance'];
				$data['type'] 			= 3;			//'0.默认1.佣金2.提现3.红包4.收付款';
				$result1 = db('mall_charge')->insert($data);
				//新增店铺余额变化
				$agent_charge = array(
					'agent_id' 		=>$user['id'],
					'type' 			=> 15,
					'tid'			=>0,
					'pt_id'			=>0,
					'message' 		=>'佣金转余额-新增余额',
					'balance' 		=>$up_money,
					'store_balance' =>$money,
					'add_time' 		=>now_time(),
					'from' 			=>1,
					'pay_type'		=>0
				);
				db('mall_charge')->insert($agent_charge);
				
				//店铺余额变化手续费
				$agent_charge2 = array(
					'agent_id' 		=>$user['id'],
					'type' 			=> 0,
					'tid'			=>0,
					'pt_id'			=>0,
					'message' 		=>'佣金转余额-手续费',
					'balance' 		=>-$poundage,
					'store_balance' =>$money,
					'add_time' 		=>now_time(),
					'from' 			=>1,
					'pay_type'		=>0
				);
				db('mall_charge')->insert($agent_charge2);
				
				//新增平台佣金
				db('member')->where('id', 1)->setInc('credit3', $poundage);
				//平台佣金变化日志
				$credit_data = array(
				'uid'			=> $user['u_id'],
				'tid' 			=> $user['id'],
				'credittype'	=> 'credit3',
				'price' 		=> $poundage,
				'remark' 		=> '收取店铺'.$user['store_name'].'佣金转余额手续费',
				'type' 			=> 16,
				"is_pt"			=> 0,
				'operator' 		=> 0,
				'order_id'		=> 0,
				'add_time' 		=> now_time(),
				'pay_type'		=> 0
				);
			db('mall_credits')->insert($credit_data);
				
				if($result1 ){
					return $this -> toJson(200, '佣金转入余额成功');
				}else{
					return $this -> toJson(408, '佣金转入余额异常');
				}
			}else{
				return $this -> toJson(404, '佣金不足');
			}
		}else{
			return $this -> toJson(404, '用户不存在');
		}
	}
/**
	 * 获取店铺信息
	 */
	 public function shopIndex(){
	 	$store_id = request() -> param('store_id');
		$storeInfo = db('info_agent')->where('id',$store_id)->find();
		if ($storeInfo) {
			$grabGoods	= Db::name('mall_goods_grab')->where('agent_id',$store_id)->order('add_time DESC')->limit(3)->select();
			$scoreGoods = Db::name('mall_goods_score')->order('add_time DESC')->limit(3)->select();
			$discountGoods  = Db::name('mall_goods_discount')->order('add_time DESC')->limit(3)->select();
			$pintuanGoods  = Db::name('mall_goods_pintuan')->order('add_time DESC')->limit(3)->select();
			
			$storeIndex['storeInfo']= $storeInfo;
			$storeIndex['scoreGoods']= $scoreGoods;
			$storeIndex['discountGoods']= $discountGoods;
			$storeIndex['pintuanGoods']= $pintuanGoods;
			
			return $this -> toJson(200, '', $storeIndex);
		} else {
			return $this -> toJson(405, '数据不存在');
		}
	 }
	 /**
	  * 商家金钱变化记录
	  */
	public function records(){
		$where['agent_id']	= input("agent_id");
		if(input("type") && input("type") ==2){		//佣金记录
			$map['type'] = ['in', '3,11,13,18'];
		}else if(input("type") && input("type") ==1){	//余额记录
			$map['type'] = ['not in', '11,13,18'];
		}
		$records=db("mall_charge")->where($where)->where($map)->select();
		return json(["list"=>$records]);
	}
	/**
	  * 商家提现记录
	  */
	public function shop_txrecord(){
		$agent_id = request() -> param('agent_id');
		$list=Db::name("mall_cashmanage")->where('uid',$agent_id)->where('user_type',2)->select();
		
		return json(["list"=>$list]);
	}
	  /* POST
	 * 申请开店
	 */
	public function post() {
		if ($this -> request -> isPost()) {
			$data=input("post.");
			$data['add_time']=now_time();
			if($data['id']){
				$result=db('info_agent')->where("id",$data['id'])->update($data);	
			}else{
				$result=db('info_agent')->insert($data);	
			}
			if($result !== false){
				db("member")->where('id', input("u_id"))->update(['agent_type' => '2']);//修改用户为为已开店
				return $this->toJson(200, '保存成功');
			}else{
				return $this->toJson(406, '保存失败');
			}
		}
	}
	/**
	 * 商家后台首页
	 */
	public function store($uid){
		$store=db('info_agent')->where('u_id',input("uid"))->find();
		$data['store']=$store;
		$data['cate']=$this->getCate();
		if(!$store){
			return $this->toJson(406, '店铺不存在',$data);
		}else{
			return $this->toJson(200, 'ok', $data);
		}		
	}
	/**
	 * POST
	 * 修改商户
	 */
	public function update(){
		if($this->request->isPost()){
        	$agent_model = new AgentModel();
			$data=input("post.");
			$result = $agent_model -> allowField(true) -> save($data,$data['id']);
			if($result !== false){
				return $this->toJson(200, '保存成功');
			}else{
				return $this->toJson(406, '保存失败');
			}
		}
	}
	/**
	 * 获取商品分类
	 */
	public function getCate(){
		if (cache('cate')) {
			$cate = cache('cate');
		} else {
			$cate = db("mall_category")->where('level',2)->select();
			cache("cate",$cate);
		}
		return $cate;
	}
	//获取商家信息
	public function get_agent(){
		$agent=db("info_agent")->find(input("store_id"));
		return json(["agent"=>$agent]);
	}
	//根据商家用户id获取商家信息
	public function exchange(){
		$agent=db("info_agent")->where("id",session("agent_id"))->find();
		//是否开通连锁店
		/*$chainstore = db('mall_chainstore')->where('agent_id',$agent['id'])->find();
		$agent['is_chainstore'] = 1;
		if($chainstore){
			$agent['is_chainstore'] = 2;
		}*/
		$this->assign('agent_info',$agent);
		return $this->fetch();
	}
	//用户鼓励金
	public function getUserScore (){
		$goodsType = request() -> param('goods_type');
		$goods_id = request() -> param('goods_id');
		$user_id = request() -> param('user_id');
		//获取商品信息
		$goodsTable = AgentController::getNumType($goodsType);
		$agent_id = Db::name($goodsTable)->where('id', $goods_id)->value('agent_id');
		
		$score = Db::name('mall_score')->where(['agent_id'=>$agent_id,'user_id' => $user_id])->sum('score');
		if($score){
			return $this->toJson(200, 'ok', $score);
		}else{
			return $this->toJson(405, '',0);
		}
	}
	//店铺前台首页
	public function store_indx(){
		$longitude = request() -> param('longitude');
		$latitude = request() -> param('latitude');
		$store_id = request() -> param('sid');
		//获取店铺信息
		$storeInfo = Db::name("info_agent")->where('id', $store_id)->find();
		if($storeInfo){
			//获取云拼团商品
			$pintuans = Db::name("line_goods")->where(['store_id'=>$store_id,'is_pt'=>1])->order('add_time','desc')->limit(2)->select();
			//获取疯狂抢商品
			$grabs = Db::name("line_goods")->where(['store_id'=>$store_id,'is_grab'=>1])->order('add_time desc')->limit(3)->select();
			//获取赚鼓励金商品
			$goods_score = Db::name("line_goods")->where('store_id', $store_id)->order('add_time desc')->limit(3)->select();
			//获取优惠购商品
			$discounts = Db::name("line_goods")->where(['store_id'=>$store_id,'is_agio'=>1])->order('add_time desc')->limit(3)->select();
			//获取连锁店信息
			$chainstore = Db::name("mall_chainstore")->where('agent_id', $store_id)->select();
			foreach($chainstore as $key=>$items){
				$distance = AgentController::GetDistance($longitude,$latitude,$items['longitude'],$items['latitude']);
				$chainstore[$key]['distance'] = $distance;
			}
			//获取商家联盟
			$unionstore = Db::name("mall_unionstore")->where('agent_id', $store_id)->select();
			$store_Info['storeInfo']  	= $storeInfo;
			$store_Info['pintuans']   	= $pintuans;
			$store_Info['grabs'] 	  	= $grabs;
			$store_Info['goods_score']  = $goods_score;
			$store_Info['discounts']  	= $discounts;
			$store_Info['chainstore'] 	= $chainstore;
			$store_Info['unionstore'] 	= $unionstore;
			return $this->toJson(200, 'ok', $store_Info);
		}else{
			return $this->toJson(405, '',"数据异常");
		}
	}
	//店铺前台首页
	public function store_shop(){
		$longitude = request() -> param('longitude');
		$latitude = request() -> param('latitude');
		$store_id = request() -> param('store_id');
		//获取菜单
		$menu = Db::name("mall_store_goodstype")->where('agent_id', $store_id)->limit(4)->select();
		//获取店铺信息
		$storeInfo = Db::name("info_agent")->where('id', $store_id)->find();
		if($storeInfo){
			//获取云拼团商品
			$pintuans = Db::name("line_goods")->where(['store_id'=>$store_id,'is_pt'=>1])->order('add_time','desc')->limit(2)->select();
			//获取连锁店信息
			$chainstore = Db::name("mall_chainstore")->where('agent_id', $store_id)->select();
			//获取最新商品
			$new_goods = Db::name("line_goods")->where('store_id',$store_id)->where('stock > 0')->order('add_time desc')->limit(4)->select();
			foreach($chainstore as $key=>$items){
				$distance = $this->GetDistance($longitude,$latitude,$items['longitude'],$items['latitude']);
				$chainstore[$key]['distance'] = $distance;
			}
			//获取商家广告
			$ads = Db::name("mall_ads")->where('agent_id', $store_id)->select();
			//检查用户是否是联盟成员
			$union_where['apply'] = 2;
			$union_where['status'] = 1;
			$union_item = db('mall_unionitem')->where('agent_id',$store_id)->where($union_where)->find();
			$new_where = '';
			
			if($union_item){
				$new_where = ' and a.union_id = '.$union_item['union_id'];
				$sql ='select a.id,a.agent_id,a.union_id,a.store_name,a.address,a.longitude,a.latitude,b.store_logo,b.ad_score,'.
						'ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-a.latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(a.latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-a.longitude*PI()/180)/2),2)))*1000) AS juli'.
						' from long_mall_unionitem  as a LEFT JOIN long_info_agent as b ON a.agent_id = b.id where a.apply = 2 and a.status = 1 and b.ad_money>0 '.$new_where.' order by juli limit 5 ';
				$union_item_list = Db::query($sql);
			}else{
				$union_item_list=null;
			}
			$store_Info['ads']  		= $ads;
			$store_Info['storeInfo']  	= $storeInfo;
			$store_Info['pintuans']   	= $pintuans;
			$store_Info['menu'] 	  	= $menu;
			$store_Info['new_goods'] 	= $new_goods;
			$store_Info['chainstore'] 	= $chainstore;
			$store_Info['unionstore'] 	= $union_item_list;
			
			return $this->toJson(200, 'ok', $store_Info);
		}else{
			return $this->toJson(405, '',"数据异常");
		}
	}
    //联盟前台首页
	public function unionstore_index(){
		$longitude = request() -> param('longitude');
		$latitude = request() -> param('latitude');
		$union_id = request() -> param('union_id');
		//获取联盟信息
		$unionstore = Db::name("mall_unionstore")->where('id', $union_id)->where('status',2)->where('state',1)->find();
		if($unionstore){
			//获取联盟轮播图
			$ads = Db::name("mall_adsmanage")->where('agent_id', $unionstore['id'])->select();
			//获取联盟店铺
			$sql ='select a.id,a.agent_id,a.store_name,a.union_id,a.lm_name,a.address,a.longitude,a.latitude,b.thumb,b.ad_score,b.template_id,b.business_scope,'.
						'ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-a.latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(a.latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-a.longitude*PI()/180)/2),2)))*1000) AS juli'.
						' from long_mall_unionitem  as a LEFT JOIN long_info_agent as b ON a.agent_id = b.id where a.apply = 2 and a.status = 1 and a.union_id ='.$unionstore['id'].'  order by juli limit 5 ';
			$union_item_list = Db::query($sql);
			
			$store_Info['ads']  		= $ads;
			$store_Info['unionstore']  	= $unionstore;
			$store_Info['union_items'] 	= $union_item_list;
			
			$store_id_list = array();
			foreach($union_item_list as $key=>$value){
				$store_id_list[] = $value['agent_id'];
			}
			$goods_list = db('line_goods')->where('store_id','in',$store_id_list)->order('add_time desc')->limit(5)->select();
			$store_Info['new_goods'] 	= $goods_list;
			
			return $this->toJson(200, 'ok', $store_Info);
		}else{
			return $this->toJson(405, '',"数据异常");
		}
	}
	//联盟商家列表
	public function unionstore_list(){
		$longitude = request() -> param('longitude');
		$latitude = request() -> param('latitude');
		$union_id = request() -> param('union_id');
		//获取商家联盟
		$unionstore = Db::name("mall_unionstore")->where('id', $union_id)->where('status',2)->find();
		if($unionstore){
			//成员列表
        	$sql ='select a.id,a.agent_id,a.union_id,a.store_name,a.address,a.longitude,a.latitude,b.thumb,b.ad_score,b.template_id,b.business_scope,'.
						'ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-a.latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(a.latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-a.longitude*PI()/180)/2),2)))*1000) AS juli'.
						' from long_mall_unionitem  as a LEFT JOIN long_info_agent as b ON a.agent_id = b.id where a.apply = 2 and a.status = 1 and a.union_id ='.$unionstore['id'].'  order by juli';
			$union_item_list = Db::query($sql);
			
			return $this->toJson(200, 'ok', $union_item_list);
		}else{
			return $this->toJson(405, '',"数据异常");
		}
	}
	//获取附近商家
	public function get_distance_store(){
		$longitude = request() -> param('longitude');
		$latitude = request() -> param('latitude');
		//$next_page = request() -> param('next_page');
				
		$next_page =  intval(input('next_page')) ? intval(input('next_page')) : 1;
		//$sql ="select agent_id,agent_name,thumb,address,business_scope,longitude,latitude from long_mall_location where (acos(sin((".$latitude."*3.1415)/180) * sin((latitude*3.1415)/180) + cos((".$latitude."*3.1415)/180) * cos((latitude*3.1415)/180) * cos((".$longitude."*3.1415)/180 - (longitude*3.1415)/180))*6370.996)<=5";
		$where = ' order by juli asc ';
		$sql = 'select agent_id,agent_name,thumb,address,business_scope,longitude,latitude,ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli from long_mall_location'.$where.' limit '.(($next_page-1)*10).',10';
		
		$resultList=Db::query($sql);
		
		/*foreach($resultList as $key=>$items){
				$distance = AgentController::GetDistance($longitude,$latitude,$items['longitude'],$items['latitude']);
				$resultList[$key]['distance'] = $distance;
			}*/
		
		if($resultList){
			return $this->toJson(200, 'ok', $resultList);
		}else{
			return $this->toJson(405, '',"数据异常");
		}
	}
	//经纬度距离
	public function GetDistance($lat1, $lng1, $lat2, $lng2){
	    $earthRadius = 6367000; 
	     $lat1 = ($lat1 * pi() ) / 180;
	     $lng1 = ($lng1 * pi() ) / 180;
	     $lat2 = ($lat2 * pi() ) / 180;
	     $lng2 = ($lng2 * pi() ) / 180;
	     $calcLongitude = $lng2 - $lng1;
	     $calcLatitude = $lat2 - $lat1;
	     $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);  $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
	     $calculatedDistance = $earthRadius * $stepTwo;
	
	     return round($calculatedDistance)/1000;
	}
	/**
	 * 获取连锁店列表
	 */
	public function get_chainstores(){
		//获取连锁店信息
		$chains_list = Db::name("mall_chainstore")->where('agent_id', input("sid"))->order('id desc')->paginate(4);
		if($chains_list){
			return $this->toJson(200, 'ok', $chains_list);
		}else{
			return $this->toJson(405, '',"数据异常");
		}
	}
	/**
	 * 添加店铺关注,收藏
	 */
	public function solicitude(){
		$agent_id 		= request() -> param('store_id');
		$uid 			= request() -> param('uid');
		$goods_id		= request() -> param('goods_id');
		$goods_lanmu	= request() -> param('goods_type');
		
		if($goods_id){
			$collect['collect_id'] 		= $goods_id;
			$collect['collect_type'] 	= 2;
		}else{
			$collect['collect_id']		= $agent_id;
			$collect['collect_type'] 	= 1;
		}
		$where['uid']	= $uid;
		$where['collect_id'] = $collect['collect_id'];
		$cut_collect = Db::name("mall_collect")->where($where)->find();
		if($cut_collect){
			return $this->toJson(200, "已关注","");
		}else{
			$collect['uid'] 			= $uid;
			$collect['goods_lanmu'] 	= $goods_lanmu;
			$result = db('mall_collect')->insert($collect);
			if($result){
				return $this->toJson(200, '关注成功！', '');
			}else{
				return $this->toJson(405, '',"数据异常");
			}
		}
	}
	 /**
	 * 获取商品类型
	 */
	 public function getNumType($num){
	 	switch ($num)
		{
		case 2:
		  return "mall_goods_discount";
		  break;  
		case 4:
		   return "mall_goods_pintuan";
		  break;
		case 3:
		   return "mall_goods_score";
		  break;
		case 1:
		   return "mall_goods_grab";
		  break;
		default:
			return null;
		 break;
		}
	}
	/**
	 * 店铺风格1
	 */
	public function store_indx1(){
		$sid 			= request() -> param('sid');
		//店铺信息
		$agent = db('info_agent')->where('id',$sid)->find();
		//菜单信息
		$result = db('mall_storemenu')
				->field('id,name,thumb,url,status,sort')
				->where('agent_id',$sid)->where('status',1)->order('sort ASC')->select();
		$data['agent_name']=$agent['store_name'];
		$data['agent_thumb']=$agent['store_logo'];
		$data['store_menu']=$result;
		return $this->toJson(200, '成功！', $data);
	}
	/**
	 * 秒杀列表
	 */
	function get_kill_goods($page=1){
		$store_id = request() -> param('store_id');
		$cut_time = date('H:i:s',time());
		$where['is_ms'] = 1;
		$where['end_time'] = ['>',$cut_time];
		$where['start_time'] = ['<',$cut_time];
		$where['store_id'] = $store_id;
		$goodsList = Db::name('line_goods')->where($where)->order('add_time desc')->paginate(4);
		if($goodsList){
			return $this -> toJson(200, '', $goodsList);
		}else{
			return $this -> toJson(405, '数据异常');
		}
	}
	/**
	 * 拼团列表
	 */
	function get_pin_goods(){
		$store_id = request() -> param('store_id');
		$where['store_id'] = $store_id;
		$goodsList = Db::name('line_goods')->where('is_pt',1)->where($where)->order('add_time desc')->paginate(4);
		if($goodsList){
			return $this -> toJson(200, '', $goodsList);
		}else{
			return $this -> toJson(405, '数据异常');
		}
	}
	//连锁店首页
	function liansuod_page(){
		//根据用户id获取店铺信息
		$agent_info = db('info_agent')->where('id',session('agent_id'))->find();
		//获取连锁店信息
		$chain_store = db('agent_store')->where('id',input('chain_id'))->find();
		/**连锁店今日收入**/
		$cut_day_money = 0;
		//线上收入
		$day_money_sql1 = "select SUM(balance) as day_money,"
		 	." SUM(CASE WHEN agent_score<0 THEN agent_score ELSE 0 END) as dayzscore,"
		 	." SUM(CASE WHEN agent_score>0 THEN agent_score ELSE 0 END) as dayfscore"
		  	." from log_paylog where state = 2 and  chain_id = ".$chain_store['id']." and to_days(add_time) = to_days(now())";
		$day_money1=db::query($day_money_sql1)[0]['day_money'];
		if($day_money1){
			$cut_day_money = bcadd($cut_day_money, $day_money1, 2);
		}
		$cut_day_zscore = 0;
		$day_zscore = db::query($day_money_sql1)[0]['dayzscore'];
		if($day_zscore){
			$cut_day_zscore = bcadd($cut_day_zscore, $day_zscore, 2);
		}
		$date['day_zscore'] = $cut_day_zscore;
		$cut_day_fscore = 0;
		$day_fscore = db::query($day_money_sql1)[0]['dayfscore'];
		if($day_fscore){
			$cut_day_fscore = bcadd($cut_day_fscore, $day_fscore, 2);
		}
		$date['day_fscore'] = $cut_day_fscore;
		
		
		/**连锁店本周收入**/
		$cut_week_money = 0;
		//线上收入
		$week_money_sql1 = "select SUM(balance) as week_money,"
		 	." SUM(CASE WHEN agent_score<0 THEN agent_score ELSE 0 END) as weekzscore,"
		 	." SUM(CASE WHEN agent_score>0 THEN agent_score ELSE 0 END) as weekfscore"
		  	." from log_paylog where state = 2 and  chain_id = ".$chain_store['id']." and YEARWEEK(date_format(add_time,'%Y-%m-%d')) = YEARWEEK(now())";
		$week_money1=db::query($week_money_sql1)[0]['week_money'];
		if($week_money1){
			$cut_week_money = bcadd($cut_week_money, $week_money1, 2);
		}
		$cut_week_zscore = 0;
		$week_zscore = db::query($week_money_sql1)[0]['weekzscore'];
		if($week_zscore){
			$cut_week_zscore = bcadd($cut_week_zscore, $week_zscore, 2);
		}
		$date['week_zscore'] = $cut_week_zscore;
		$cut_week_fscore = 0;
		$week_fscore = db::query($week_money_sql1)[0]['weekfscore'];
		if($week_fscore){
			$cut_week_fscore = bcadd($cut_week_fscore, $week_fscore, 2);
		}
		$date['week_fscore'] = $cut_week_fscore;
		
		/**连锁店本月收入**/
		$cut_moon_money = 0;
		//线上收入
		$moon_money_sql1 = "select SUM(balance) as moon_money,"
		 	." SUM(CASE WHEN agent_score<0 THEN agent_score ELSE 0 END) as moonzscore,"
		 	." SUM(CASE WHEN agent_score>0 THEN agent_score ELSE 0 END) as moonfscore"
		  	." from log_paylog where state=2 and  order_type NOT IN ('3','4','5','6') and chain_id = ".$chain_store['id']." and date_format(add_time,'%Y-%m')=date_format(now(),'%Y-%m')";
		$moon_money1=db::query($moon_money_sql1)[0]['moon_money'];
		if($moon_money1){
			$cut_moon_money = bcadd($cut_moon_money, $moon_money1, 2);
		}
		$cut_moon_zscore = 0;
		$moon_zscore = db::query($moon_money_sql1)[0]['moonzscore'];
		if($moon_zscore){
			$cut_moon_zscore = bcadd($cut_moon_zscore, $moon_zscore, 2);
		}
		$date['moon_zscore'] = $cut_moon_zscore;
		$cut_moon_fscore = 0;
		$moon_fscore = db::query($moon_money_sql1)[0]['moonfscore'];
		if($moon_fscore){
			$cut_moon_fscore = bcadd($cut_moon_fscore, $moon_fscore, 2);
		}
		$date['moon_fscore'] = $cut_moon_fscore;
		
		/**连锁店累计销售**/
		$cut_total_money=0;
		$total_money_sql = "select SUM(balance) as total_money  from log_paylog where state=2 and order_type not in (3,4,5) and chain_id = ".$chain_store['id'];
		$total_money=db::query($total_money_sql)[0]['total_money'];
		if($total_money){
			$cut_total_money = bcadd($cut_total_money, $total_money, 2);
		}
		$date['day_money'] 		= $cut_day_money;
		$date['week_money']		= $cut_week_money;
		$date['moon_money'] 	= $cut_moon_money;
		$date['total_money'] 	= $cut_total_money;
		$date['chain_store'] 	= $chain_store;
		$date['agent_info'] 	= $agent_info;
		$date['code_url'] 		= "http://".$_SERVER['HTTP_HOST']."/index/pay/qrcode_pay?agent_id=".$agent_info['id']."&store_id=".$chain_store['id']."&clerk_id=0";
		
		$this->assign('date',$date);
		return $this->fetch();
	}
	//获取连锁店信息
	function myshop_lsdedit(){
		//根据用户id获取店铺信息
		$chain_info = db('agent_store')->alias('a')
						->field('a.id,a.store_name,a.addres,b.no,b.name as empname,c.logo')
						->join('info_agent c','a.agent_id=c.id','LEFT')
						->join('agent_clerk b','a.id=b.chain_id','LEFT')		
						->where('a.id',input('chain_id'))
						->find();
		$this->assign('chain_info',$chain_info);
		return $this->fetch();
	}
	//获取所有连锁店
	function chain_list(){
		//根据用户id获取店铺信息
		$agent_info = db('info_agent')->where('id',session('agent_id'))->find();
		$chain_list = db('mall_chainstore')->where('agent_id',$agent_info['id'])->select();
		if($chain_list){
			$list_info = array();
			for($i=0;$i<count($chain_list);$i++){
				/**连锁店累计销售**/
				$cut_total_money=0;
				$total_money_sql = "select SUM(price) as total_money  from long_mall_corepaylog where chain_id = ".$chain_list[$i]['id'];
				$total_money=db::query($total_money_sql)[0]['total_money'];
				if($total_money){
					$cut_total_money = bcadd($cut_total_money, $total_money, 2);
				}
				
				$chain['total_money'] 		= $cut_total_money;
				$chain['chain_store'] 		= $chain_list[$i];
				$date['agent_info'] 		= $agent_info;
				$list_info['chain_list'][] 	= $chain;
			}
				$list_info['agent_info'] = $agent_info;
			return $this -> toJson(200, '',$list_info);
		}else{
			return $this -> toJson(401, '连锁店不存在');
		}
		
	}
	//删除连锁店信息
	function del_chain(){
		$res = db('agent_store')->where('id', input('chain_id'))->delete();
		if($res){
			return json(["code"=>200,"msg"=>"删除成功"]);
		}else{
			return json(["code"=>402,"msg"=>"删除失败"]);
		}
	}
	//修改连锁店信息
	function up_chain(){
		$chain_info = db('agent_store')->where('id', input('chain_id'))->find();
		if($chain_info){
			//修改店铺信息
			$update['store_name'] = input('name');
			$update['addres'] = input('address');
			$res = db('agent_store')->where('id', $chain_info['id'])->update($update);
			if($res){
				/*// 获取短信模板
				$template = db('sms_template') -> find(10);
				$msg['name'] = '';
				//获取分店负责人信息
				$employee_info = db('line_employee')->where('no',$chain_info['emp_no'])->where('chainstore_id',$chain_info['id'])->find();
				//发送短信，提醒分店负责人
				$msg = send_sms($employee_info['mobile'], $template['tid'], json_encode($msg), $template['sign_name']);
				//发送短信，提醒分店负责人
				$msg = send_sms(input('mobile'), $template['tid'], json_encode($msg), $template['sign_name']);*/
				return json(["code"=>200,"msg"=>"修改成功"]);
			}else{
				return json(["code"=>402,"msg"=>"修改失败"]);
			}
			
		}else{
			return json(["code"=>401,"msg"=>"门店不存在"]);
		}
	}
	//统计收银
	public function tj_sy(){
		$agent_id=input("agent_id");
		$type=input("type");
		if($type==2){//按周
			$time="DATE_FORMAT(add_time,'%Y-%v')";
		}else if($type==3){//按月
			$time="DATE_FORMAT(add_time,'%Y-%m')";
		}else{//按日
			$time="DATE_FORMAT(add_time,'%Y-%m-%d')";
		}
		$sql=" select $time days,DATE_FORMAT(add_time,'%Y-%m-%d-%H-%i-%s') time,id,price,agent_score,type, 1 as my_sum";
		$sql.=" from long_mall_corepaylog where  tid=$agent_id and type in ('ads_order','score_pay') group by time order by days desc";
		$tables=Db::query($sql);
		//修改数组值
		foreach($tables as  $key=>$value){
			
			$tables[$key]['avg_price'] = $tables[$key]['price'];
			
			if($value['type'] == 'score_pay'){
				$tables[$key]['agent_score'] = $tables[$key]['price'];
				$tables[$key]['price'] = 0;
			}
		}
		//重组数组
		$list = array();
		foreach($tables as  $key=>$value){
			$list[$value['days']][] = $value;
		}
		//数组排版
		$dat_list = array();
		foreach($list as $key=>$value){
			
			$new_array = array('price' =>0,'agent_score'=>0,'avg_price'=>0);
			
			foreach($value as $item=>$val){
				$new_array['price'] 		= bcadd($new_array['price'], $val['price'], 2);
				$new_array['agent_score'] 	= bcadd($new_array['agent_score'], $val['agent_score'], 2);
				$new_array['avg_price'] 	= bcadd($new_array['avg_price'], $val['avg_price'], 2);
				
			}
			$new_array2['days'] 	= $key;
			$new_array2['count'] 	= count($value);
			$new_array2['avg'] 		= bcdiv($new_array['avg_price'], count($value), 2);
			$new_array2['price'] 	= $new_array['price'];
			$new_array2['score'] 	= $new_array['agent_score'];
			
			$dat_list[] = $new_array2;
		}
		return json(["list"=>$dat_list]);
	}
	//新增连锁店
	function myshop_lsdadd(){
		//根据用户id获取店铺信息
		$agent_info = db('info_agent')->where('id',session('agent_id'))->find();
		if($agent_info && $_POST){
			$chain_data['store_name'] 		= input('name');
			$chain_data['addres'] 			= input('address');
			$chain_data['agent_id'] 		= $agent_info['id'];
			$chain_data['longitude'] 		= $agent_info['id'];
			$chain_data['latitude'] 		= $agent_info['id'];
			$chain_data['add_time'] 		= now_time();
			$chain_data['oem_id'] 			= $agent_info['oem_id'];
			$up_res = db('agent_store')->insert($chain_data);
			if($up_res){
				return json(["code"=>200,"msg"=>"添加成功"]);
			}else{
				return json(["code"=>402,"msg"=>"添加失败"]);
			}
		}
		$this->assign('agent_info',$agent_info);
		return  $this->fetch();
	}
	//获取用户加入的所有联盟信息
	function user_union_list(){
		//根据用户id 获取用户店铺信息
		$agent_info = db('info_agent')->where('u_id',input('uid'))->find();
		//查找用户加入的所有联盟
		$union_items_where['b.agent_id'] 	= $agent_info['id'];
		$union_items_where['b.status'] 	= 1;
		$union_list = db('mall_unionstore')->alias('a')
						->join('mall_unionitem b','a.id=b.union_id','LEFT')
						->field('a.id as un_id,a.thumb as un_logo, a.name as un_name,a.address as un_address,a.tel as un_tel,a.status as un_status,a.unnion_ads_money as un_money,a.scope as un_scope,a.agent_id as un_main_id,a.store_name as un_store_name,b.apply,b.agent_id')
						->where($union_items_where)
						->group('b.union_id')->select();
		if(count($union_list)>0){
			return $this -> toJson(200, '', $union_list);
		}else{
			return $this -> toJson(402, '');
		}
	}
	//检查用户是否已创建联盟
	function user_union_main(){
		//根据用户id查找商家信息
		$agent_info = db('info_agent')->where('u_id',input('uid'))->find();
		//获取用户创建联盟信息
		$union_main = db('mall_unionstore')->where('agent_id',$agent_info['id'])->where('status','in','1,2')->find();
		//检查用户是否创建联盟，且联盟未解散
		if($union_main && $union_main['state'] != 3){
			return $this -> toJson(201, '', $union_main);
		}else{
			return $this -> toJson(202, '');
		}
	}
	
	//连锁店的收款记录
	function chain_record(){
		$chain_id = input('chain_id');  	
		$page=1;
		if(input("page")){
			$page=input("page");
		}
		$begin=($page-1)*10;
		$record_list = db('log_paylog')
						->where('chain_id',input('chain_id'))
						->where('order_type','not in','3,4,5')
						->where('state',2)
						->order('add_time desc')
						->limit($begin,20)
						->select();			
		return json(["list"=>$record_list]);
	}
	
	//连锁店销售记录
	function liansuod_record(){
		$this->assign('chain_id',input('chain_id'));
		return $this->fetch();
	}
	
	//订单详情
	function liansuod_jypage(){
		$order_sn = input('order_sn');  	
		$order_info = db('log_paylog')->where('order_sn',$order_sn)->where('state',2)->find();
		$this->assign('order_info',$order_info);
		return $this->fetch();
	}
	
	//连锁店收款记录
	function chain_sy(){
		$agent_id=input("agent_id");
		$where=" a.tid=".input("agent_id");
		if(input("chain_id")){
			$where .=" and a.chain_id = ".input("chain_id");
		}
		$sql =" select m.mobile,g.store_name,h.name,DATE_FORMAT(a.add_time,'%Y-%m-%d') days,a.add_time,a.id,a.tid,a.price,a.chain_id from long_mall_corepaylog a"; 
		$sql.=" left join long_member m on a.uid = m.id ";
		$sql.=" left join long_info_agent g on a.tid = g.id ";
		$sql.=" left join long_mall_chainstore h on a.chain_id = h.id ";
		$sql.=" where $where order by days desc ";
		$list=Db::query($sql);
		$chains=db("mall_chainstore")->where("agent_id",$agent_id)->select();
		$data=array();
		foreach($list as $k){
			if(!isset($data[$k['days']]['totals'])){
				$data[$k['days']]['totals']=0;
			}
			$data[$k['days']][]=$k;
			$data[$k['days']]['totals']+=$k['price'];
		}
		return json(["list"=>$data,"chains"=>$chains]);
	}
	//获取连锁店交易详情
	function record_detail(){
		//根据用户id获取店铺信息
		$agent_info = db('info_agent')->where('id',session('agent_id'))->find();
		//获取连锁店信息
		$chain_store = db('mall_chainstore')->where('id',input('chain_id'))->find();
		if($agent_info && $chain_store && $agent_info['id'] == $chain_store['agent_id']){
			//判断数据库表
			if(input('line') == 1){
				$record_detail = db('line_paylog')->where('id',input('id'))->find();
			}else if(input('line') == 2){
				$record_detail = db('mall_corepaylog')->where('id',input('id'))->find();
			}else{
				return $this -> toJson(403, '数据异常');
			}
			//返回交易记录
			if($record_detail){
				return $this -> toJson(200, '',$record_detail);
			}else{
				return $this -> toJson(404, '数据异常');
			}
		}else{
			return $this -> toJson(402, '未开通该连锁店');
		}
	}
	//员工管理
	function employeemagelist(){
		//根据用户id获取店铺信息
		$agent_info = db('info_agent')->where('id',session('agent_id'))->find();
		//获取连锁店信息
		$employee_list = db('line_employee')->alias('a')
		->join('mall_chainstore b','a.chainstore_id=b.id','LEFT')
		->join('line_zhiwei c','a.z_id=c.id','LEFT')
		->field('a.id,a.name as ygname,c.name as zwname,b.name')
		->where('a.agent_id',$agent_info['id'])->select();
		if($agent_info && $employee_list ){
			$data['employee_list'] = $employee_list;
			return $this -> toJson(200, '',$data);
		}else{
			return $this -> toJson(402, '暂无记录');
		}
	}

	//获取员工信息
	function employee_memedit(){
		//获取收银员信息
		$clerk_info = db('agent_clerk')->where('id',input('clerk_id'))->find();
		//获取门店信息
		$store_info = db('agent_store')->where('state',1)->where('agent_id',$clerk_info['agent_id'])->select();

		$this->assign('clerk_info',$clerk_info);
		$this->assign('agent_store',$store_info);
		return $this->fetch();
	}
	//获取员工
	public function get_emplist(){
		$emplist = db("line_employee")->field("id,name,no,mobile")->where('chainstore_id',input('chain_id'))->select();
		return json(["emplist"=>$emplist]);
	}
	/**
	 * 编辑员工
	 */
	public function edite_emp(){		
		$emp_info = db('agent_clerk')->where('id', input('emp_id'))->find();
		if($emp_info){
			$param = input();
			//修改员工信息
			$union_data['no'] 				= $param['no'];
			$union_data['mobile'] 			= $param['mobile'];
			$union_data['chain_id'] 		= $param['chain_id'];
			$union_data['ctype'] 			= $param['z_id'];
			$union_data['name'] 			= $param['name'];
			
			$res = db('agent_clerk')->where('id', $emp_info['id'])->update($union_data);
			if($res){
				return json(["code"=>200,"msg"=>"修改成功"]);
			}else{
				return json(["code"=>402,"msg"=>"修改失败"]);
			}
		}else{
			return json(["code"=>403,"msg"=>"员工不存在"]);
		}
    }
	/**
     * [del删除]
     * @author [longx] 
     */
	function del_emp(){	
		$res = db('agent_clerk')->where('id', input('emp_id'))->delete();
		if($res){
			return json(["code"=>200,"msg"=>"删除成功"]);
		}else{
			return json(["code"=>402,"msg"=>"删除失败"]);
		}
	}
	
	//商品列表
	function goods_list(){
		$goods_list = db('agent_goods')
						->where('agent_id',session('agent_id'))
						->where('goods_state','<>',3)
						->order('addtime desc')
						->paginate(20);
						
		$this->assign('goods_list',$goods_list);
		
		return $this->fetch();
	}
	
	//添加商品
    public function goods_add(){
    	//获取当前商家信息
    	if(request()->isPost()){
    		$param=input('post.');
			$param['addtime'] 	= now_time();
			$param['agent_id'] 	= session('agent_id');
			$param['oem_id']  	= config("cut_oem_id");
			$agent_goods = new GoodsModel();
			$res = $agent_goods->allowField(true)->save($param);
			if($res){
				return json(['code'=>200,'msg'=>'添加成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'添加失败']);
			}
			
    	}
		//获取平台分类
		$platform_type = Db::table('sys_platform_type')->select();
		//1级分类
		$platform_1 = array();
		//2级分类
		$platform_2 = array();
		foreach($platform_type as $key=>$values){
			if($values['pid'] == 0){
				$platform_1[] = $values;
			}else{
				$platform_2[$values['pid']][] = $values;
			}
		}
		$this->assign('platform_1',$platform_1);
		$this->assign('platform_2',$platform_2);
		//获取商家分类
		$agent_type = Db::table('agent_type')->where('agent_id',session('agent_id'))->select();
		$this->assign('agent_type',$agent_type);
		$storelist=db('agent_store')->where('agent_id',session('agent_id'))->where('state',1)->select();
		$this->assign('storelist',$storelist);
		
    	return $this->fetch();
    }

	//修改商品
    public function goods_edit(){
    	
		if(request()->isPost()){
			$param=input('post.');
			$agent_goods = new GoodsModel();
			$res = $agent_goods->allowField(true)->save($param,$param['id']);
			
			if($res){
				return json(['code'=>200,'msg'=>'修改成功']);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
			
		}
    	$goods_id = input('goods_id');
		$goods_info = db('agent_goods')
						->alias('a')
						->join('agent_type b','a.trade_id = b.id','left')
						->where('a.id',$goods_id)
						->find();
		if($goods_info){
			//商品信息
			$goods_info['content'] = html_entity_decode($goods_info['content']);
			$goods_info['goods_id'] = $goods_id;
			$this->assign('goods_info',$goods_info);
			
			//获取平台分类
			$platform_type = Db::table('sys_platform_type')->select();
			//1级分类
			$platform_1 = array();
			//2级分类
			$platform_2 = array();
			foreach($platform_type as $key=>$values){
				if($values['pid'] == 0){
					$platform_1[] = $values;
				}else{
					$platform_2[$values['pid']][] = $values;
				}
			}
			$this->assign('platform_1',$platform_1);
			$this->assign('platform_2',$platform_2);
			//获取商家分类
			$agent_type = Db::table('agent_type')->where('agent_id',session('agent_id'))->select();
			$this->assign('agent_type',$agent_type);
			$storelist=db('agent_store')->where('agent_id',session('agent_id'))->where('state',1)->select();
			$this->assign('storelist',$storelist);
			
		}else{
			$this->error('商品不存在');
		}
		
		return $this->fetch();
    }

	//删除商品
	function del_goods(){
		
		$id = input('goods_id');
		
		$res = db('agent_goods')->where('id',$id)->update(['goods_state'=>3]);
		if($res){
			$this->success('删除成功');
		}else{
			$this->error('删除失败');
		}
		
	}
	
	//商品上下架
	function godos_state(){
		$id = input('goods_id');
		$type = input('type');
		
		$res = db('agent_goods')->where('id',$id)->update(['goods_state'=>$type]);
		if($res){
			$this->success('修改成功');
		}else{
			$this->error('修改失败');
		}
	}
	
	//鼓励金兑现
    public function score_yue(){
    	
    	$agent=db('info_agent')->where('id',session("agent_id"))->find();
		$agent_id=$agent['id'];
    	if($_POST){
			$ex_num=input("value")*10;
			if($agent['score']<=$ex_num){
				return json(["code"=>400,'msg'=>'鼓励金不足']);
			}
			$fee=0.05;//服务费率
			$ex_price=$ex_num*(1-$fee)/10;//鼓励金转余额多少
			$sql="update info_agent set score = score-$ex_num,total_income=total_income+$ex_price,balance = balance + $ex_price where id=$agent_id and score>0";
			$res=DB::execute($sql);
			if($res){
				$data = array(
				'agent_id'		=> $agent['id'],
				'order_type' 	=> 6,
				'message' 	 	=> '鼓励金兑换到余额',
			    'balance' 	 	=> $ex_price,
			    'pay_type' 	 	=> 5,
			    'status_tinyint'=> 1,
			    'oem_id' 	 	=> $agent['oem_id'],
			    'agency_id' 	=> $agent['agency_id1'],
			    'city_id' 	 	=> $agent['agency_id2'],
			    "add_time"	 	=> now_time()
				);
				db('log_agent_charge')->insert($data);
				$data = array(
					'agent_id'		=> $agent['id'],
					'order_type' 	=> 6,
					'message' 	 	=> "鼓励金兑换到余额扣除鼓励金",
				    'balance' 	 	=> -$ex_num,
				    "add_time"	 	=> now_time()
				);
				db('log_agent_score')->insert($data);
				$agent_much=$ex_num*($fee)/10;//鼓励金兑换到余额手续费
				admin_charge($agent_much,1,0,$agent_id,'商家鼓励金兑换到余额');
				return json(['code'=>200,'msg'=>'操作成功']);
			}else{
				return json(['code'=>400,'msg'=>'操作失败']);
			}
    	}
		$this->assign('agent',$agent);
    	return $this->fetch();
    }
    
    //商家余额记录
    function yue_record(){
    	
    	$bance_list = db('log_agent_charge')
    						->where('agent_id',session("agent_id"))
    						->select();
    	
    	
    	$this->assign('bance_list',$bance_list);
    	return $this->fetch();
    }
    
    public function wang_upload(){
		include_once ('././vendor/aliyun-oss-php-sdk/autoload.php');
			foreach ($_FILES as $name => $file) {
				$info = getimagesize($file['tmp_name']);  
        		$ext = image_type_to_extension($info['2']);  
				$ossClient = new \OSS\OssClient('LTAIaqGtJ3JDXJvv', 'Q2kTcyepAHX0VOR44OtszVoyOKE8gl', 'oss-cn-shanghai.aliyuncs.com');
				$name=time()."_".rand(100000, 999999).$ext;
				try{
					$res=$ossClient->uploadFile("long3",$name,$file['tmp_name']);
					$result['code'] = 1;
					$result['msg'] = '上传成功！';
					$result['src']='http://long3.oss-cn-shanghai.aliyuncs.com/'.$name;
				} catch(OssException $e) {
					$result['code'] = 0;
					$result['msg'] = $file -> $e->getMessage();
				}
			}
		return json($result);
	}
    
    //余额提现
    function yue_tixian(){
    	//获取当前商家信息
    	$agent_info =db('info_agent')->where('id',session("agent_id"))->find();
    	$this->assign('agent_info',$agent_info);
    	if(request()->isPost()){
			$result = true;
    		// 启动事务
			Db::startTrans();			
			try{
				//商家累计收入
				$agent_total_money = db('log_agent_charge')
											->where('agent_id',$agent_info['id'])
											->where('order_type','<>',7)
											->where('order_type','<>',10)
											->where('balance','>',0)
											->sum('balance');
				//检查累计收入 
				if(bccomp($agent_total_money, $agent_info['total_income'], 4) != 0){
					return json(['code'=>405,'msg'=>'提交申请失败']);
				}
				//计算商家余额 = 累计收入 - 提现金额
				$agent_cut_money = bcsub($agent_total_money, $agent_info['total_withdrawals_money'], 4);
				//检查商家余额 
				if(bccomp($agent_cut_money, $agent_info['balance'], 2) != 0){
					return json(['code'=>403,'msg'=>'提交申请失败']);
				}
				//检查提现金额，核对余额是否合法
				if(bccomp($agent_info['balance'], $_POST['tixian_money'], 4)>=0){
					//计算当前余额
					$cut_balance = bcsub($agent_info['balance'], $_POST['tixian_money'], 2);
					//更新商家信息
					$rest1 = db('info_agent')
								->where('id', $agent_info['id'])
								->update([
									'balance'=>$cut_balance
									]);
					if(!$rest1)$result =false;
					
					//商家提现，余额变化日志
					$rest2 = agent_money_change($agent_info['id'],0,0,0,5,-$_POST['tixian_money'],'余额提现',0);
					if(!$rest2)$result =false;
					
					//提现日志
					$rest3 = withdrawals_log($agent_info['id'],1,$_POST['tixian_money'],$_POST['tixian_money'],$rest2);
					if(!$rest3)$result =false;
					
					if($result){
						// 提交事务
	    				Db::commit();
	    				
	    				$tem_w['title']='提现申请';
						$tem=db("sms_template")->where($tem_w)->find();
						$msg=sendsms($tem['sign_name'],config('send_mobile'),$tem['tid'],'code','');
	    				
						return json(['code'=>200,'msg'=>'提交成功']);
					}else{
						//回滚
			    		Db::rollback();
						return json(['code'=>402,'msg'=>'提交失败']);
					}
				}else{
					return json(['code'=>402,'msg'=>'提交失败']);
				}
			}catch ( Exception $e ) {
			    //$e->getMessage();
			    //回滚
			    Db::rollback();
			    exit;
			}
    	}
    	return $this->fetch();
    }
}
